﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestService.Host
{
    public class ServerRunnable
    {
        private static ServerRunnable _instance = null;
        private static object _lockObj = new object();

        private ServerRunnable() { }

        public static ServerRunnable Instance
        {
            get
            {
                if (_instance == null)
                    lock (_lockObj)
                        if (_instance == null)
                            _instance = new ServerRunnable();
                return _instance;
            }
        }

        private const int _diff = 50;

        public void Run()
        {
            int fristTime = Environment.TickCount;
            int currentTime = 0, sleepTime = 0;

            while (!ServerManager.IsStop())
            {
                currentTime = Environment.TickCount;
                int diff = 0;
                if (fristTime > currentTime)
                    diff = (int.MaxValue - fristTime) + (currentTime - int.MinValue) + 1;
                else
                    diff = currentTime - fristTime;

                ServerManager.Instance.Update(diff);
                fristTime = currentTime;

                //当时间间隔大于控制时间间隔时回调
                if (diff <= (_diff + sleepTime))
                {
                    sleepTime = _diff + sleepTime - diff;
                    Thread.Sleep(sleepTime);
                }
                else
                    sleepTime = 0;
            }
            //停止淘宝监听服务
            ServerManager.Instance.KillAll();
        }
    }
}
